package com.zrj.auth.core.enhancer;

import com.zrj.auth.core.userdetails.mobile.MemberUserDetails;
import com.zrj.auth.core.userdetails.user.SysUserDetails;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT内容增强器
 * @author zhaorujie
 */
@Configuration
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Object principal = authentication.getPrincipal();
        Map<String, Object> info = new HashMap<>(16);
        if(principal instanceof SysUserDetails) {
            SysUserDetails securityUserDetails = (SysUserDetails) authentication.getPrincipal();
            //把用户ID设置到JWT中
            info.put("userId", securityUserDetails.getUserId());
            try {
                info.put("username", URLEncoder.encode(securityUserDetails.getUsername(), StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {}
        } else if (principal instanceof MemberUserDetails){
            MemberUserDetails memberUserDetails = (MemberUserDetails) principal;
            info.put("memberId", memberUserDetails.getMemberId());
            info.put("username", memberUserDetails.getUsername());
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
